// https://leetcode.cn/problems/minimum-depth-of-binary-tree/
// Created by ade on 2022/7/19.
//
#include <iostream>
#include <vector>


using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    int minDepth(TreeNode *root) {
        if(!root) return 0;
        if(!root->left) return 1 + minDepth(root->right);
        if(!root->right) return 1 + minDepth(root->left);
        return 1 + min(minDepth(root->left) , minDepth(root->right));
    }

    int getHeight(TreeNode *root) {
        if (root) {
            return max(getHeight(root->left), getHeight(root->right)) + 1;
        }
        return 0;
    }

    int dfs(TreeNode *root, int index) {
        if (root) {
            if (root->left == nullptr) {
                return dfs(root->right, index + 1) + index;
            } else if (root->right == nullptr) {
                return dfs(root->left, index + 1) + index;
            } else {
                return min(getHeight(root->left), getHeight(root->right)) + index;
            }
        }
        return 0;
    }


    TreeNode *init() {
        // [1,2,2,3,3,null,null,4,4]
        TreeNode *head1 = new TreeNode(1);
        TreeNode *head2 = new TreeNode(2);
        TreeNode *head3 = new TreeNode(2);
        TreeNode *head4 = new TreeNode(3);
        TreeNode *head5 = new TreeNode(3);
        TreeNode *head6 = new TreeNode(4);
        TreeNode *head7 = new TreeNode(4);
        head1->left = head2;
        head1->right = head3;
        head2->left = head4;
        head2->right = head4;
        head3->left = nullptr;
        head3->right = nullptr;
        head4->left = head6;
        head4->right = head6;
        return head1;
    }
};

int main() {
    Solution so;
    TreeNode *head = so.init();
    int res = so.minDepth(head);
    cout << res << endl;
    return 0;
}